package com.educationx;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.util.PreferenceConnector;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TabHost;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CourseActivity extends Activity {
	private TabHost tabs;
	TextView textviewcoursetitle;
	TextView textviewdescription;
	TextView textviewinstructor;
	TextView textviewratingscore;
	TextView textviewtags;
	Button buttonenroll;
	RatingBar ratingbar;
	RatingBar ratingbarcurrent;
	EditText  edittextcomment;
	String courseid;
	ListView listcomments;
	ListView listlectures;
	Messenger messenger;
	ArrayList<Lecture> lecturelist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_course);

		tabs = (TabHost)findViewById(R.id.tabhost);
		tabs.setup();
		
		TabHost.TabSpec spec = tabs.newTabSpec("tag1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Details");
		tabs.addTab(spec);

		spec = tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("Ratings & Comments");
		tabs.addTab(spec);
		
		courseid = getIntent().getStringExtra("id");

		textviewcoursetitle = (TextView) findViewById(R.id.textViewCourseTitle);
		textviewdescription = (TextView) findViewById(R.id.textViewDescription);
		textviewinstructor = (TextView) findViewById(R.id.textViewInstructer);
		textviewratingscore = (TextView) findViewById(R.id.textViewRatingScore);
		textviewtags = (TextView) findViewById(R.id.textViewTags);
		buttonenroll = (Button) findViewById(R.id.buttonEnroll);
		ratingbar = (RatingBar) findViewById(R.id.ratingBar);
		ratingbarcurrent = (RatingBar) findViewById(R.id.ratingBarCurrent);
		edittextcomment = (EditText) findViewById(R.id.editTextComment);
		listcomments = (ListView) findViewById(android.R.id.list);
		listlectures = (ListView) findViewById(R.id.listLectures);
		
		messenger = new Messenger(handler);
		
		lecturelist = new ArrayList<Lecture>();
		
		Intent intent_coursesdetail_service = new Intent(getApplicationContext(), CourseDetailService.class);
		intent_coursesdetail_service.putExtra("messenger", messenger);
		intent_coursesdetail_service.putExtra("userID", PreferenceConnector.readString(getApplicationContext(), "id", "0"));
		intent_coursesdetail_service.putExtra("courseID", courseid);
		startService(intent_coursesdetail_service);

		Intent intent_commentlist_service = new Intent(getApplicationContext(), CourseCommentsListService.class);
		intent_commentlist_service.putExtra("messenger", messenger);
		intent_commentlist_service.putExtra("courseID", courseid);
		startService(intent_commentlist_service);

		ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				if(fromUser) {
					Intent intent_rate_service = new Intent(getApplicationContext(), RateService.class);
					Messenger messenger = new Messenger(handler);
					intent_rate_service.putExtra("messenger", messenger);
					intent_rate_service.putExtra("userID", PreferenceConnector.readString(getApplicationContext(), "id", "0"));
					intent_rate_service.putExtra("courseID", courseid);
					intent_rate_service.putExtra("rating", String.valueOf(Math.round(rating)));
					startService(intent_rate_service);
				}
			}
		});
	}

	public void goToBack(View view) {
		this.finish();
	}

	public void enroll(View view) {
		if(buttonenroll.isEnabled()) {
			Intent intent_comment_service = new Intent(getApplicationContext(), EnrollService.class);
			intent_comment_service.putExtra("messenger", messenger);
			intent_comment_service.putExtra("userID", PreferenceConnector.readString(getApplicationContext(), "id", "0"));
			intent_comment_service.putExtra("courseID", courseid);
			startService(intent_comment_service);
		}
	}

	public void comment(View view) {
		Intent intent_comment_service = new Intent(getApplicationContext(), CommentService.class);
		intent_comment_service.putExtra("messenger", messenger);
		intent_comment_service.putExtra("userID", PreferenceConnector.readString(getApplicationContext(), "id", "0"));
		intent_comment_service.putExtra("courseID", courseid);
		intent_comment_service.putExtra("comment", edittextcomment.getText().toString());
		startService(intent_comment_service);

		edittextcomment.setText("");
	}

	private Handler handler = new Handler() {

		public void handleMessage(Message message) {
			if(message.obj == null) {
				Toast.makeText(getApplicationContext(), "Failed to send data. Servers are temporarily " +
						" down.", Toast.LENGTH_LONG).show();
			}
			else if(message.arg1 == Services.COURSE_DETAIL) {
				JSONObject jsonResponse;
				try {
					jsonResponse = new JSONObject(message.obj.toString());
					textviewcoursetitle.setText(jsonResponse.getString("courseName"));
					textviewdescription.setText(jsonResponse.getString("courseDescription"));
					textviewratingscore.setText("(" + jsonResponse.getString("courseRating") + ")");
					ratingbarcurrent.setEnabled(false);
					ratingbarcurrent.setRating(Float.valueOf(jsonResponse.getString("courseRating")));
					textviewinstructor.setText("Instructor: " + jsonResponse.getString("courseCreatorName"));
					textviewtags.setText("Tags: ");
					
					JSONArray tags = jsonResponse.getJSONArray("courseTags");
					for(int i = 0; i < tags.length(); i++) {
						textviewtags.setText(textviewtags.getText().toString() + tags.getJSONObject(i).getString("tagName") + ", ");
					}
					
					JSONArray lectures = jsonResponse.getJSONArray("courseLectures");
					for(int i = 0; i < lectures.length(); i++ ) {
						lecturelist.add(new Lecture(lectures.getJSONObject(i).getString("lectureName"),
													lectures.getJSONObject(i).getString("lectureLink")));
					}
					LectureListArrayAdapter listAdapter = new LectureListArrayAdapter(CourseActivity.this, R.layout.row_lecture, lecturelist);
					listlectures.setAdapter(listAdapter);
					listlectures.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							Intent goToLectureActivity = new Intent(CourseActivity.this, LectureActivity.class);
							goToLectureActivity.putExtra("title", lecturelist.get(arg2).getName());
							goToLectureActivity.putExtra("link", lecturelist.get(arg2).getLink());
							startActivity(goToLectureActivity);
						}
					});
					
					if(jsonResponse.getString("userEnrolled").equals("true")) {
						buttonenroll.setEnabled(false);
					}
					if(jsonResponse.getString("userRated").equals("true")) {
						ratingbar.setRating(Integer.valueOf(jsonResponse.getString("userRatePoint")));
						ratingbar.setEnabled(false);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}	
			}
			else if(message.arg1 == Services.RATE) {
				if(message.obj.toString().equals("1\n")) {
					Toast.makeText(getApplicationContext(), "Your rating is accepted.", Toast.LENGTH_LONG).show();
					ratingbar.setEnabled(false);
				} else {
					Toast.makeText(getApplicationContext(), "Your rating is NOT accepted. You must subscribe this course" +
							" before rating.", Toast.LENGTH_LONG).show();
				}
			} else if(message.arg1 == Services.COMMENT) {
				if(message.obj.toString().equals("1\n")) {
					Toast.makeText(getApplicationContext(), "Your comment is accepted.", Toast.LENGTH_LONG).show();
					Intent intent_commentlist_service = new Intent(getApplicationContext(), CourseCommentsListService.class);
					intent_commentlist_service.putExtra("messenger", messenger);
					intent_commentlist_service.putExtra("courseID", courseid);
					startService(intent_commentlist_service);
				} else {
					Toast.makeText(getApplicationContext(), "Your comment is NOT accepted. You must subscribe this course" +
							" before commenting.", Toast.LENGTH_LONG).show();
				}
			} else if(message.arg1 == Services.COURSE_COMMENTS) {
				List<Comment> comments = new ArrayList<Comment>();
				try {
					JSONObject jsonResponse = new JSONObject(message.obj.toString());
					JSONArray jsonArray = jsonResponse.getJSONArray("courseCommentsList");

					for(int i = jsonArray.length() - 1; i >= 0; i--) {
						String text = jsonArray.getJSONObject(i).getString("commentDetail");
						String date = jsonArray.getJSONObject(i).getString("commentDate");
						String commenter = jsonArray.getJSONObject(i).getString("commentUserName");

						comments.add(new Comment(text, date, commenter));
					}
					CommentListArrayAdapter listAdapter = new CommentListArrayAdapter(CourseActivity.this, R.layout.row_comment, comments);
					listcomments.setAdapter(listAdapter);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else if(message.arg1 == Services.ENROLL) {
				if(message.obj.toString().equals("1\n")) {
					buttonenroll.setEnabled(false);
					Toast.makeText(getApplicationContext(), "You have succesfully subscribed this course.", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getApplicationContext(), "You have failed to subscribe this course. Caused by a" +
							" internal conflict. Please contact our support.", Toast.LENGTH_LONG).show();
				}
			}
		}
	};
}
